# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import sys

import gvn.changebranch
import gvn.cmdline
import gvn.description
import gvn.diff
import gvn.util


helptext__gvn_review = """review: Review a revision or changebranch.
usage: review CHANGE | REVISION
"""


def Handle_GvnReview(ctx):
  ctx.wc_operands = False
  for reviewable in ctx.operands:
    if gvn.util.IsValidChangeName(reviewable):
      # XXX Ugh, Description gets a ChangeBranch and then we get a
      # second one here.
      print gvn.description.Description(ctx.config, ctx.project,
                                        reviewable).Output()

      (username, name, revision) = gvn.util.ParseChangeName(reviewable)
      gvn.changebranch.Diff(ctx.project.repository,
                            gvn.changebranch.ChangeBranch(ctx.config,
                                                          ctx.project,
                                                          name,
                                                          username,
                                                          revision),
                            sys.stdout,
                            ctx.config.diff_command,
                            pool=ctx.pool)

    elif gvn.util.MatchRevision(reviewable):
      if reviewable[0] == 'r':
        reviewable = reviewable[1:]
      print gvn.description.Description(ctx.config, ctx.project,
                                        reviewable).Output()
      gvn.diff.RunSvnDiff(ctx.config, ['-c', reviewable,
                                       ctx.project.repository.URL()])

    else:
      raise gvn.errors.BadOperands('\n'.join([
                "invalid operand: '%s'" % reviewable,
                "neither a change name nor a revision number"
                ]))

  return 0


gvn.cmdline.AddCommand('review', Handle_GvnReview, helptext__gvn_review,
                       gvn.cmdline.AuthOptions(['project']))
